/** Concrete implementation Repository for Property objects
 *
 *  @author Scott Monahan
 *  @version $Id$
 *  
 *  File last changed on $Date:$ by $Author:$ in $Rev:$
 *
 */

package info637.pprc.repository;

import java.util.List;

import org.apache.log4j.Logger;
import org.springframework.stereotype.Component;

import info637.pprc.model.Property;

@Component(value = "propertyRepository")
public class PropertyRepository extends AbstractListBasedRepository<Property, AbstractPropertyFilter> 
	implements IPropertyRepository {
	
	static Logger log = Logger.getLogger(PropertyRepository.class.getName());
	
	@Override
	public List<Property> findByPublicFilterData(String address, String city,
		String state, String zip, String monthlyRent) {

		return this.fetch(new PublicPropertyFilter(
			new Property(address, city, state, zip, monthlyRent))
		);
	}
	
	@Override
	public List<Property> findByAdminFilterData(String propertyName,
		String tenantName, String balance) {

		return this.fetch(new AdminPropertyFilter(
			new Property(propertyName, tenantName, balance))
		);
	}
	
	@Override
	public boolean addProperty(Property propertyToAdd) {
		
		boolean retVal = false;
		boolean addressExists = false;
		
		// TODO: This is really the validation that would occur
		// when the insert is attempted and the new data violates
		// a unique key constraint
		
		List<Property> allProperties = this.fetchAll();
		
		for (Property property : allProperties) {
			
			String existingKey = property.getAddress() + property.getCity() 
				+ property.getState() + property.getZip();
			
			String newKey = propertyToAdd.getAddress() + propertyToAdd.getCity() 
					+ propertyToAdd.getState() + propertyToAdd.getZip();
			
			log.debug("New Property Key: [" + existingKey + "]");
			
			log.debug("Existing Property Key: [" + existingKey + "]");
			
			if (existingKey.equalsIgnoreCase(newKey)) {
				
				log.debug("Keys found to be the same, so not adding");
				
				addressExists = true;
			}
		}
		
		if (!addressExists) {
			
			log.debug("Adding Property: [" + propertyToAdd.getAddress() + "]");
			
			retVal = this.add(propertyToAdd);
		}
		
		return retVal;
	}

	@Override
	public boolean updateProperty(Property propertyToUpdate) {
		
		boolean retVal = false;
		
		Property property = findByPropertyId(propertyToUpdate.getId());
		
		if (property != null) {
			
			retVal = this.update(property, propertyToUpdate);
		}
		
		return retVal;
	}

	@Override
	public Property findByPropertyId(String propertyId) {
		
		Property out = null;
		
		List<Property> allProperties = this.fetchAll();
		
		for (Property property : allProperties) {

			if (property.getId().equalsIgnoreCase(propertyId)) {
				
				out = property;
				
				break;
			}
		}
		
		return out;
	}

	@Override
	public boolean isEmpty() {
		
		if (this.fetchAll().size() == 0) {
			
			return true;
			
		} else {
			
			return false;
		}
	}
}
